package cn.edu.hpu.jie.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import cn.edu.hpu.jie.entity.Active;
import cn.edu.hpu.jie.services.ActiveService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ActiveAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private Active active;
	private int type;
	private String title;
	private String content;
	private Map<String, Object> session = ActionContext.getContext().getSession();
	private HttpServletResponse response = ServletActionContext.getResponse();
	
	public String getActiveType1() {
		type = 1;
		return getActiveByType();
	}
	
	public String getActiveType2() {
		type = 2;
		return getActiveByType();
	}
	
	public String editActive2() throws IOException {
		type = 2;
		return editActive();
	}
	
	public String editActive1() throws IOException {
		type = 1;
		return editActive();
	}
	
	private String getActiveByType() {
		if(type != 0) {
			active = new ActiveService().getActiveByType(type);
			return SUCCESS;
		}
		
		return ERROR;
	}
	
	private String editActive() throws IOException {
		if("POST".equals(ServletActionContext.getRequest().getMethod()) && type != 0 && title != null && content != null) {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			int loginid = (Integer) session.get("loginid");
			active = new ActiveService().getActiveByType(type);
			int lines = 0;
			if(active == null) {
				lines = insertActiveByType(loginid);
			} else {
				active.setContent(content);
				active.setTitle(title);
				active.setType(type);
				String path = ServletActionContext.getServletContext().getRealPath("/");
				lines = new ActiveService().editActive(active, path, loginid);
			}
			
			out.print(lines);
			return null;
		}
		
		return ERROR;
	}
	
	private int insertActiveByType(int loginid) {
		Active a = new Active();
		a.setContent(content);
		a.setTitle(title);
		a.setType(type);
		String path = ServletActionContext.getServletContext().getRealPath("/");
		return new ActiveService().insertActive(a, path, loginid);
	}
	//get & set
	public Active getActive() {
		return this.active;
	}

	public void setActive(Active active) {
		this.active = active;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setContent(String content) {
		this.content = content;
	}
	
}
